package com.car.loan.project.xr.service.impl;

import com.car.loan.common.exception.loan.LoanParameterException;
import com.car.loan.common.utils.SecurityUtils;
import com.car.loan.framework.web.domain.AjaxResult;
import com.car.loan.project.xr.domain.LoanDetail;
import com.car.loan.project.xr.domain.LoanStatus;
import com.car.loan.project.xr.mapper.LoanDetailMapper;
import com.car.loan.project.xr.mapper.LoanStatusMapper;
import com.car.loan.project.xr.util.bo.business.ContractAuditBo;
import com.car.loan.project.xr.util.enums.ContractAuditStatus;
import java.time.LocalDateTime;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author huangding
 * @description
 * @date 2019/12/22 21:05
 */
@Service
public class LoanContractAuditService {

    @Autowired
    private LoanStatusMapper loanStatusMapper;

    @Autowired
    private LoanDetailMapper loanDetailMapper;


    public AjaxResult audit(ContractAuditBo contractAuditBo) {
        long loanId = Long.parseLong(contractAuditBo.getLoanId());
        Optional<LoanStatus> optionalLoanStatus = loanStatusMapper.selectByLoanId(loanId);
        LoanStatus loanStatus = optionalLoanStatus
            .orElseThrow(() -> new LoanParameterException("该业务状态数据异常，请联系管理员"));

        Long contractAuditStatus = loanStatus.getContractAuditStatus();
        if (ContractAuditStatus.INIT.status != contractAuditStatus) {
            return AjaxResult.error("当前状态不可提交");
        }
        loanStatus.setContractAuditStatus(contractAuditBo.getOperatorStatus());
        loanStatus.setContractAuditTime(LocalDateTime.now());
        loanStatus.setContractAuditId(SecurityUtils.getLoginUserId());
        loanStatusMapper.updateById(loanStatus);

        Optional<LoanDetail> optionalLoanDetail = loanDetailMapper.selectByLoanId(loanId);
        LoanDetail loanDetail = optionalLoanDetail.get();
        loanDetail.setContractDate(contractAuditBo.getContractDate());
        loanDetailMapper.updateById(loanDetail);
        return AjaxResult.success();
    }
}
